#include <cstring>
#include <cstdlib>

#include "InputBuffer.h"
#include "../tools/Log.h"

using namespace std;

/*	If handle_line is a member function of another class, instance refers to the desired instance
	of that class. In that case, make handle_line a static member function and modify it so that it
	takes an instance of the class (the instance will be the first parameter). If not, simply pass
	NULL and ignore the first argument of your handle_line.
*/
InputBuffer::InputBuffer(int fd, void (*handle_line)(const char *)) :
	fd(fd), cur(0), instance(instance), handle_line(handle_line)
{ }

void InputBuffer::process()
{
	char *ret;
	
	if (cur >= (INPUT_BUFFER_SIZE - 1)) {
		lout << "WARNING: InputBuffer - Process_user_input error:  buffer full;  line too long!" << endl;
		return;
	}

	int nread = read(fd, buf + cur, (INPUT_BUFFER_SIZE - cur));
	
	if (nread > 0)
		cur += nread;
	
	while ((ret = strchr(buf, '\n')) != NULL)
	{
		*ret = '\0';
		handle_line(buf);
		
		// Shift the remaining contents of the buffer forward
		memmove(buf, ret + 1, INPUT_BUFFER_SIZE - (ret - buf));
		cur -= (ret - buf + 1);
	}
}
